package com.demo.webservicedemo.service.Impl;

import com.demo.webservicedemo.entity.GMItemCreate;
import com.demo.webservicedemo.entity.MaterialEntry;
import com.demo.webservicedemo.mapper.MaterialEntryMapper;
import com.demo.webservicedemo.service.MaterialEntryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class MaterialEntryServiceImpl implements MaterialEntryService {

    @Autowired
    private MaterialEntryMapper mapper;


    @Transactional
    public int createEntry(GMItemCreate gmItemCreate) {
        MaterialEntry entry = new MaterialEntry();
        entry.setOrderId(gmItemCreate.getORDERID());
        entry.setMaterial(gmItemCreate.getMATERIAL());
        entry.setEntryQnt(gmItemCreate.getENTRY_QNT());
        entry.setBatch(gmItemCreate.getBATCH());
        //BeanUtils.copyProperties(gmItemCreate,entry);
        //判断是否已经有Order ID ，有则进行更新，无则添加
        MaterialEntry existing = mapper.selectByUniqueKey(entry.getOrderId());
        if (existing != null) {
          return  mapper.update(entry);
        }

        return mapper.insert(entry);
    }

    @Transactional
    public int updateEntry(MaterialEntry entry) {
        MaterialEntry existing = mapper.selectById(entry.getId());
        if (existing == null) {
            throw new RuntimeException("记录不存在");
        }
        return mapper.update(entry);
    }

    @Transactional
    public int deleteEntry(Integer id) {
        return mapper.delete(id);
    }

    public MaterialEntry getEntry(Integer id) {
        return mapper.selectById(id);
    }

}
